package com.jvxb.demo.controller;

import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Redis控制器
 *
 * @author jvxb
 * @since 2022-12-26
 */
@Api(tags = "redis控制器")
@RestController
@RequestMapping("redis")
public class RedisController {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/set")
    public Object set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
        return "success";
    }

    @GetMapping("/get")
    public Object get(String key) {
        Object value = redisTemplate.opsForValue().get(key);
        return value;
    }

    @GetMapping("/del")
    public Object del(String key) {
        Object value = redisTemplate.delete(key);
        return value;
    }

    @GetMapping("/hset")
    public Object hset(String key, String hashKey, String value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        return "success";
    }

    @GetMapping("/hget")
    public Object hget(String key, String hashKey) {
        Object value = redisTemplate.opsForHash().get(key, hashKey);
        return value;
    }

    @GetMapping("/cacheable")
    @Cacheable(value = "cacheTest", key = "#id")
    public String cacheable(String id) {
        System.out.println("执行方法-save/find缓存");
        if (id == null) return "null id";
        return "your id = " + id;
    }

    @GetMapping("/cachePut")
    @CachePut(value = "cacheTest", key = "#id")
    public String cachePut(String id) {
        System.out.println("执行方法-save缓存");
        if (id == null) return "null id";
        return "your id = " + id;
    }

    @GetMapping("cacheEvict")
    @CacheEvict(value = "cacheTest", key = "#id")
    public String cacheEvict(String id) {
        System.out.println("执行方法-evict缓存");
        if (id == null) return "null id";
        return "your id = " + id;
    }

}
